package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    UserMapper userMapper;
    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    //userLoginDTO中只有一个code数据，用于单次请求openid
    public User wxLogin(UserLoginDTO userLoginDTO) {

        String openid = getOpenid(userLoginDTO.getCode());

        //判断是否为空，为空抛出异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断openid在数据库中是否存在
        User user = userMapper.selectByOpenid(openid);

        //若不存在则注册，即向数据库中插入数据
        if(user == null){
            user = User.builder().openid(openid).createTime(LocalDateTime.now()).build();

            //插入数据后，将得到的id值返回到对象中，此工作在mapper中做
            userMapper.insert(user);
        }

        return user;
    }

    private String getOpenid(String code) {
        //发送请求，向微信请求用户openid
        Map<String, String> map = new HashMap<String, String>();
        map.put("grant_type", "authorization_code");
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        String res = HttpClientUtil.doGet(WX_LOGIN_URL, map);

        //取出openid
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");
        return openid;
    }


}
